#!/bin/bash
#
# Copyright (c) 2020 NVI, Inc.
#
# This file is part of FSL10 Linux distribution.
# (see http://github.com/nvi-inc/fsl10).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#

# For systems with GPT LVM RAID arrays, drops the first disk out of the
# /dev/md0 array to allow non destructive testing in a convenient way.

usage() { echo "Usage: $0 [-h]"; echo -e "  \t-h\tdisplay this help and exit"; }

while getopts "h" arg; do
	case $a in
		h | *)
			usage
			exit 0
			;;
	esac
done

if [ ! -b /dev/md0 ]; then
        echo "ERROR: RAID /dev/md0 does not exist!!"
        exit 1
fi
if ! mdadm --detail /dev/md0 2>&1 | grep -qE ": (clean|active) $" ; then
        echo "ERROR: RAID /dev/md0 is not in a clean or active state!"
        exit 1
fi

# Perform sanity checks on primary disk first
if ! mdadm --detail /dev/md0 | grep -q /dev/sda2; then
        echo "ERROR: \"Primary\" disk /dev/sda is not part of RAID /dev/md0!!"
	exit 1
fi
if [ "$(cat /sys/block/sda/removable)" != "0" ]; then
	echo "WARNING: \"Primary\" disk /dev/sda is removable:"
	echo -n " /dev/sda: "$(lsblk --nodeps -no tran /dev/sda | tr [:lower:] [:upper:]) 
	echo -n " "$(lsblk --nodeps -no type /dev/sda)
	echo -n ", model" $(lsblk --nodeps -no model /dev/sda)
	echo ", s/n "$(lsblk --nodeps -no serial /dev/sda)
	echo -n "Press <Enter> if you wish to continue (Control-C aborts) "
	read $ans
fi

while ! mdadm --detail /dev/md0 2>&1 | grep -q ": clean $" ; do
	echo -ne "\rWaiting for a clean state ... "
	sync;sync
	sleep 1;
done
echo -ne "\r                              \r"
sync;sync
sleep 1;
mdadm /dev/md0 -f /dev/sda2
